#!/bin/bash
set -eux

is_leader="$(is-leader)"
if [ "$is_leader" = "False" ]; then
    juju-log -l INFO "I'm not leader"
    status-set active "Not leader" || true
    exit 0
fi

juju-log -l INFO "It me, $JUJU_UNIT_NAME"
status-set maintenance "Getting token" || true
token="$(config-get token)"
relation-set --app app-token="$JUJU_UNIT_NAME $token"

if [[ -z "$token" ]]; then
  juju-log -l WARNING "Blocked: set the token"
  status-set blocked "Set the token" || true
else
  juju-log -l INFO "Token is $token"
  status-set active "Token is $(echo $token | cut -c 1-20)" || true
fi
